const app = getApp()
const CONFIG = app.globalData.config;

Page({

    data: {
        // keyWord
        // hideSearchHover // 确认搜索后用以判断隐藏搜索浮层显示搜索结果
        imgUrl: app.globalData.imgUrl,
        searchHistoryList: [],
        filterList: app.globalData.filterList
    },

    onLoad: function (options) {
        this.setData({
            searchHistoryList: wx.getStorageSync('SEARCH_HISTORY_LIST') || []
        })
    },

    onShow: function () {

    },

    onReachBottom: function () {

    },

    search: function (keyWord) {
        this.setData({
            hideSearchHover: true
        })
    },

    handleFouce: function() {
        this.setData({
            hideSearchHover: false
        });
    },

    handleConfirm: function (e) {
        const keyWord = e.detail.value;
        this.search(keyWord);
        let searchHistoryList = this.data.searchHistoryList;
        let isHas = false;
        for (let index = 0, len = searchHistoryList.length; index < len; index++) {
            if (keyWord === searchHistoryList[index].value) {
                searchHistoryList = searchHistoryList.splice(index, 1).concat(searchHistoryList);
                isHas = true;
                break;
            }
        }

        if (!isHas) {
            searchHistoryList.unshift({
                id: new Date().getTime(),
                value: keyWord
            });

            if (searchHistoryList.length > CONFIG.HISTORY_LIST_COUNT) {
                searchHistoryList = searchHistoryList.slice(0, CONFIG.HISTORY_LIST_COUNT);
            }
        }
        
        this.setData({
            searchHistoryList: searchHistoryList
        });

        wx.setStorageSync('SEARCH_HISTORY_LIST', searchHistoryList);
    },

    clearItem: function(e) {
        const index = e.target.dataset.index;

        this.data.searchHistoryList.splice(index, 1);
        this.setData({
            searchHistoryList: this.data.searchHistoryList
        });

        wx.setStorageSync('SEARCH_HISTORY_LIST', this.data.searchHistoryList);
    },

    selectSearchItem: function(e) {
        const index = e.target.dataset.index;
        let searchHistoryList = this.data.searchHistoryList;
        searchHistoryList = searchHistoryList.splice(index, 1).concat(searchHistoryList);

        this.search(searchHistoryList[0].value);
        this.setData({
            keyWord: searchHistoryList[0].value,
            searchHistoryList: searchHistoryList
        });
        
        wx.setStorageSync('SEARCH_HISTORY_LIST', searchHistoryList);
    }
})